// 提供复用逻辑的函数
/**
 * target dom对象
 * apiFn  请求接口
 */
import { useIntersectionObserver, useIntervalFn } from '@vueuse/core'
import { ref, onUnmounted } from 'vue'
import dayjs from 'dayjs'

export const useLazyDate = (apiFn) => {
    const result = ref([])
    const target = ref(null)
    // stop 停止观察
    const { stop } = useIntersectionObserver(
        target,
        ([{ isIntersecting }], observerElement) => {
            // isIntersecting 是否进入可视区
            if (isIntersecting) {
                stop()
                // 调用api获取数据
                apiFn().then(data => {
                    result.value = data.result
                })
            }
        }, {
        // threshold 容器和可视区交叉的占比 取值，0-1 之间，默认比0大
        threshold: 0
    }
    )
    return { result, target }
}

/**
 * 支付倒计时函数
 */
export const usePayTime = () => {
    // 倒计时逻辑
    const time = ref(0)
    const timeText = ref('')
    const { pause, resume } = useIntervalFn(() => {
        time.value--
        timeText.value = dayjs.unix(time.value).format('mm分ss秒')
        if (time.value <= 0) {
            pause()
        }
    }, 1000, false)
    onUnmounted(() => {
        pause()
    })

    // 开启定时器 countdown 倒计时时间
    const start = (countdown) => {
        time.value = countdown
        timeText.value = dayjs.unix(time.value).format('mm分ss秒')
        resume()
    }

    return {
        start,
        timeText
    }
}